package main

import (
	"chapter-03-mutual_auth/service"
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"io/ioutil"
	"log"
	"os"
	"path"
)

func main() {
	//获取当前目录
	//获取当前目录
	dir, err := os.Getwd()
	if err != nil {
		grpclog.Fatalf("Failed to get current directory: %v", err)
	}
	// TLS认证
	//从证书相关文件中读取和解析信息，得到证书公钥、密钥对
	cert, _ := tls.LoadX509KeyPair(path.Join(dir, "/key/client.pem"), path.Join(dir, "/key/client.key"))
	//初始化一个CertPool
	certPool := x509.NewCertPool()
	ca, _ := ioutil.ReadFile(path.Join(dir, "/key/ca.pem"))
	//注意这里只能解析pem类型的根证书，所以需要的是ca.pem
	//解析传入的证书，解析成功会将其加到池子中
	certPool.AppendCertsFromPEM(ca)
	// 构建基于 TLS 的 TransportCredentials 选项
	creds := credentials.NewTLS(&tls.Config{
		// 设置证书链，允许包含一个或多个
		Certificates: []tls.Certificate{cert},
		ServerName:   "ximu.info", //注意这里的参数为配置文件中所允许的ServerName，也就是其中配置的DNS...
		RootCAs:      certPool,
	})

	dial, err := grpc.Dial("127.0.0.1:9090", grpc.WithTransportCredentials(creds))
	if err != nil {
		panic(err)
	}
	defer func(dial *grpc.ClientConn) {
		err := dial.Close()
		if err != nil {
			panic(err)
		}
	}(dial)

	// do something
	client := service.NewSayHelloClient(dial)

	resp, err := client.SayHello(context.Background(), &service.HelloRequest{Id: "1"})

	if err != nil {
		log.Fatal("调用gRPC方法错误: ", err)
	}
	marshal, _ := json.Marshal(resp)
	log.Println("双向认证：调用gRPC方法成功，ProdStock = ", string(marshal))

}
